import cv2


def thresh(img):
    img_gray = cv2.GaussianBlur(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
    # img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # rt, img_th = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
    img_th = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 3, 2)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
    opening = cv2.morphologyEx(img_th, cv2.MORPH_OPEN, kernel)
    cv2.imshow('open', opening)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
    closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations = 3)
    cv2.imshow('close', closing)
    return img_th

